<template>
  <div>
    <el-dialog v-model="dialogVisible" append-to-body>
      <template #header>
        <div class="header">
          <span style="margin-right: 10px">附件</span>
          <el-button type="primary" plain :icon="Plus" size="small" @click="handleAddAnnex"
            >新增</el-button
          >
        </div>
      </template>
      <art-table
        :data="attachments"
        :loading="loading"
        :currentPage="form.page"
        :pageSize="form.size"
        :total="total"
        :height="attachments.length === 0 ? 400 : 'auto'"
      >
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            {{ scope.row.type === 1 ? '图片' : '视频' }}
          </template>
        </el-table-column>
        <el-table-column label="封面" align="center" prop="cover">
          <template #default="scope">
            <ArtImagePreview :src="scope.row.cover" :preview-type="1"></ArtImagePreview>
            <div
              v-if="scope.row.type == 2"
              class="video-box"
              :style="{ backgroundImage: `url(${scope.row.cover})` }"
              @click="handlePlay(scope.row)"
            >
              <i class="el-icon-video-play icon-play"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort">
          <template #default="scope">
            <div @click="updateSort(scope.row)" style="cursor: pointer">
              <div v-if="sortForm.id != scope.row.id">
                {{ scope.row.sort }}
              </div>
              <el-input
                v-else
                v-model="scope.row.sort"
                class="centered-input"
                ref="inputRef"
                @blur="blurFun(scope.row)"
                placeholder="请输入排序"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="160"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button size="small" text :icon="Edit" @click="handleEditAnnex(scope.row)"
              >修改</el-button
            >
            <el-button size="small" text :icon="Delete" @click="handleDelAnnex(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </art-table>
    </el-dialog>
    <!-- 新增修改附件 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      v-model="open"
      append-to-body
      width="500px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="label" prop="file_url">
          <ArtVideoUpload v-model="form.file_url" v-if="type == 2"></ArtVideoUpload>
          <ArtImageUpload v-model:files="form.file_url" v-if="type == 1"></ArtImageUpload>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="" v-model:visible="videoShow" append-to-body>
      <ArtVideoPlayer :src="videoUrl"></ArtVideoPlayer>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, toRaw } from 'vue'
  import { Plus, Edit, Delete } from '@element-plus/icons-vue'
  import { FormInstance, FormRules } from 'element-plus'
  import { AttachService } from '@/api/common/attach'
  import { createBaseConfig } from '@/config/core/base-config'
  import { deepClone } from '@/utils/utils'

  const dialogVisible = ref(false)
  const loading = ref(false)
  const total = ref(0)
  const prefix = createBaseConfig().prefix

  const props = withDefaults(
    defineProps<{
      title?: string
      label?: string
      type: number | string
    }>(),
    {
      title: '附件',
      label: '附件',
      type: 1
    }
  )
  const emit = defineEmits(['submitForm', 'cancel'])
  interface FormType {
    page: number
    size: number
    file_url: string
    sort: number
    type?: number | string
    id?: number
    content_id?: number
  }
  const form = reactive<FormType>({
    page: 1,
    size: 10,
    file_url: '',
    sort: 10
  })
  const sortForm = ref<any>({})
  const cover = ref('')
  const open = ref(false)
  const videoShow = ref(false)
  const videoUrl = ref('')
  const attachments = ref([])
  const inputRef = ref(null)
  const rules = reactive<FormRules>({
    file_url: [{ required: true, message: '请上传附件', trigger: 'blur' }]
  })

  // 显示附件列表
  const openList = (id: number, cov: string) => {
    dialogVisible.value = true
    form.content_id = id
    form.type = props.type
    cover.value = cov
    getAnnexList()
  }
  // 获取附件列表
  const getAnnexList = async () => {
    loading.value = true
    const res = await AttachService.getAttachList(form)
    res.data.data.forEach((item: any) => {
      if (item.type === 2) {
        item.cover = cover.value
      } else {
        item.cover = item.file_url
      }
    })
    total.value = res.data.total
    attachments.value = res.data.data
    loading.value = false
    console.log('attachments', attachments.value.length)
  }
  // 新增附件
  const handleAddAnnex = () => {
    form.file_url = undefined
    form.id = undefined
    form.sort = 10
    open.value = true
  }
  // 修改附件
  const handleEditAnnex = (row: any) => {
    form.id = row.id
    form.sort = row.sort
    form.file_url = row.file_url.startsWith('http') ? row.file_url : prefix + row.file_url
    open.value = true
  }
  // 删除附件
  const handleDelAnnex = (row: any) => {
    ElMessageBox.confirm('是否确认删除附件', '删除附件', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return AttachService.delAttach(row.id)
      })
      .then(() => {
        getAnnexList()
        ElMessage.success('删除成功')
      })
  }
  // 视频点击播放
  const handlePlay = (row: any) => {
    if (row.file_url.startsWith('http')) {
      videoUrl.value = row.file_url
    } else {
      videoUrl.value = prefix + row.file_url
    }
    videoShow.value = true
  }
  const updateSort = async (row: any) => {
    if (sortForm.value.id == '' || sortForm.value.id == undefined) {
      sortForm.value.id = row.id
      sortForm.value.sort = row.sort
      await nextTick()
      inputRef.value.focus()
    }
  }
  const blurFun = async (row: any) => {
    if (row.sort != sortForm.value.sort) {
      const form = { id: row.id, sort: row.sort || 10 }
      await AttachService.updateContentSort(form)
      ElMessage.success('修改成功')
      sortForm.value = {}
      getAnnexList()
    } else {
      sortForm.value = {}
    }
  }
  const formRef = ref<FormInstance>()

  // 附件表单提交
  const submitForm = async () => {
    const myFrom = deepClone(toRaw(form))
    myFrom.file_url = myFrom.file_url.replace(prefix, '')
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        if (myFrom.id) {
          await AttachService.updateAttach(myFrom)
        } else {
          await AttachService.addAttach(myFrom)
        }
        ElMessage.success(myFrom.id ? '修改成功' : '新增成功')
        await getAnnexList()
        open.value = false
        emit('submitForm', form)
      }
    })
  }

  const cancel = () => {
    open.value = false
    emit('cancel')
  }
  defineExpose({
    openList
  })
</script>

<style scoped lang="scss"></style>
